import { useRef, useEffect } from 'react';
import { toast } from 'sonner';

interface SimpleRichTextEditorProps {
  value: string;
  onChange: (content: string) => void;
  placeholder?: string;
  height?: number;
  disabled?: boolean;
}

export default function SimpleRichTextEditor({
  value,
  onChange,
  placeholder = '请输入内容...',
  height = 400,
  disabled = false
}: SimpleRichTextEditorProps) {
  const editorRef = useRef<HTMLDivElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const documentInputRef = useRef<HTMLInputElement>(null);

  // 初始化编辑器内容
  useEffect(() => {
    if (editorRef.current && !editorRef.current.innerHTML) {
      editorRef.current.innerHTML = value || `<p>${placeholder}</p>`;
    }
  }, []);

  // 当 value 改变时更新内容
  useEffect(() => {
    if (editorRef.current) {
      // 只有当内容真的不同时才更新，避免光标位置丢失
      const currentContent = editorRef.current.innerHTML;
      const newContent = value || `<p>${placeholder}</p>`;

      if (currentContent !== newContent && document.activeElement !== editorRef.current) {
        editorRef.current.innerHTML = newContent;
      }
    }
  }, [value, placeholder]);

  const handleInput = () => {
    if (editorRef.current) {
      onChange(editorRef.current.innerHTML);
    }
  };

  const execCommand = (command: string, value?: string) => {
    document.execCommand(command, false, value);
    editorRef.current?.focus();
    // 延迟触发更新，确保DOM已经更新
    setTimeout(() => {
      handleInput();
    }, 10);
  };

  const insertHtml = (html: string) => {
    if (editorRef.current) {
      editorRef.current.focus();

      // 获取当前选择或光标位置
      const selection = window.getSelection();
      let range: Range;

      if (selection && selection.rangeCount > 0) {
        range = selection.getRangeAt(0);

        // 确保选择在编辑器内
        if (!editorRef.current.contains(range.commonAncestorContainer)) {
          // 如果选择不在编辑器内，创建新的range在编辑器末尾
          range = document.createRange();
          range.selectNodeContents(editorRef.current);
          range.collapse(false);
        }
      } else {
        // 如果没有选择，创建新的range在编辑器末尾
        range = document.createRange();
        range.selectNodeContents(editorRef.current);
        range.collapse(false);
      }

      // 删除当前选择的内容
      range.deleteContents();

      // 创建临时容器来解析HTML
      const tempDiv = document.createElement('div');
      tempDiv.innerHTML = html;

      // 插入所有节点
      const fragment = document.createDocumentFragment();
      while (tempDiv.firstChild) {
        fragment.appendChild(tempDiv.firstChild);
      }
      range.insertNode(fragment);

      // 移动光标到插入内容之后
      range.collapse(false);
      selection?.removeAllRanges();
      selection?.addRange(range);

      // 立即触发更新
      setTimeout(() => {
        handleInput();
      }, 0);
    }
  };

  const handleImageUpload = async (file: File) => {
    if (!file.type.startsWith('image/')) {
      toast.error('请选择图片文件');
      return;
    }

    if (file.size > 5 * 1024 * 1024) {
      toast.error('图片大小不能超过5MB');
      return;
    }

    const formData = new FormData();
    formData.append('file', file);

    try {
      // 获取认证token
      const token = localStorage.getItem('access_token');
      if (!token) {
        toast.error('请先登录');
        return;
      }

      const response = await fetch('/api/upload/image', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
        body: formData,
      });

      if (!response.ok) {
        if (response.status === 401) {
          toast.error('认证失败，请重新登录');
          return;
        }
        throw new Error('上传失败');
      }

      const result = await response.json();

      // 插入图片到编辑器
      const img = `<img src="${result.file_url}" alt="上传的图片" style="max-width: 100%; height: auto; margin: 10px 0;" />`;

      // 直接更新编辑器内容
      if (editorRef.current) {
        const currentContent = editorRef.current.innerHTML;
        const newContent = currentContent + img;
        editorRef.current.innerHTML = newContent;

        // 立即触发onChange
        onChange(newContent);

        // 将光标移到末尾
        const range = document.createRange();
        const selection = window.getSelection();
        range.selectNodeContents(editorRef.current);
        range.collapse(false);
        selection?.removeAllRanges();
        selection?.addRange(range);

        editorRef.current.focus();
      }

      toast.success('图片上传成功');
    } catch (error) {
      console.error('图片上传失败:', error);
      toast.error('图片上传失败');
    }
  };

  const handleDocumentUpload = async (file: File) => {
    // 检查文件类型
    const allowedTypes = [
      'application/pdf',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'application/vnd.ms-powerpoint',
      'application/vnd.openxmlformats-officedocument.presentationml.presentation'
    ];

    if (!allowedTypes.includes(file.type)) {
      toast.error('请选择PDF、Word、Excel或PowerPoint文件');
      return;
    }

    if (file.size > 30 * 1024 * 1024) {
      toast.error('文件大小不能超过30MB');
      return;
    }

    const formData = new FormData();
    formData.append('file', file);

    try {
      // 获取认证token
      const token = localStorage.getItem('access_token');
      if (!token) {
        toast.error('请先登录');
        return;
      }

      const response = await fetch('/api/upload/document', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
        body: formData,
      });

      if (!response.ok) {
        if (response.status === 401) {
          toast.error('认证失败，请重新登录');
          return;
        }
        throw new Error('上传失败');
      }

      const result = await response.json();

      // 获取文件图标
      const getFileIcon = (filename: string) => {
        const ext = filename.split('.').pop()?.toLowerCase();
        switch (ext) {
          case 'pdf': return 'fa-file-pdf';
          case 'doc':
          case 'docx': return 'fa-file-word';
          case 'xls':
          case 'xlsx': return 'fa-file-excel';
          case 'ppt':
          case 'pptx': return 'fa-file-powerpoint';
          default: return 'fa-file';
        }
      };

      // 插入文档链接到编辑器
      const documentLink = `<div style="display: inline-block; margin: 10px 0; padding: 10px; border: 1px solid #ddd; border-radius: 4px; background-color: #f9f9f9;">
        <i class="fa-solid ${getFileIcon(result.original_filename)}" style="margin-right: 8px; color: #666;"></i>
        <a href="${result.file_url}" target="_blank" download="${result.original_filename}" style="text-decoration: none; color: #007bff;">
          ${result.original_filename}
        </a>
        <span style="margin-left: 8px; color: #666; font-size: 0.9em;">(${(result.file_size / 1024).toFixed(1)} KB)</span>
      </div>`;

      insertHtml(documentLink);
      toast.success('文档上传成功');
    } catch (error) {
      console.error('文档上传失败:', error);
      toast.error('文档上传失败');
    }
  };

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      handleImageUpload(file);
    }
    // 清空文件输入，允许重复选择同一文件
    e.target.value = '';
  };

  const handleDocumentSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      handleDocumentUpload(file);
    }
    // 清空文件输入，允许重复选择同一文件
    e.target.value = '';
  };

  const insertImage = () => {
    fileInputRef.current?.click();
  };

  const insertDocument = () => {
    documentInputRef.current?.click();
  };

  const insertLink = () => {
    const url = prompt('请输入链接地址:');
    if (url) {
      execCommand('createLink', url);
    }
  };

  const insertTable = () => {
    const rows = prompt('请输入行数:', '3');
    const cols = prompt('请输入列数:', '3');
    
    if (rows && cols) {
      const rowCount = parseInt(rows);
      const colCount = parseInt(cols);
      
      let tableHTML = '<table border="1" style="border-collapse: collapse; width: 100%; margin: 10px 0;">';
      
      for (let i = 0; i < rowCount; i++) {
        tableHTML += '<tr>';
        for (let j = 0; j < colCount; j++) {
          tableHTML += '<td style="padding: 8px; border: 1px solid #ddd;">&nbsp;</td>';
        }
        tableHTML += '</tr>';
      }
      
      tableHTML += '</table>';
      insertHtml(tableHTML);
    }
  };

  return (
    <div className="border border-gray-300 rounded-lg overflow-hidden">
      {/* 工具栏 */}
      <div className="bg-gray-50 border-b border-gray-300 p-2 flex flex-wrap gap-1">
        <button
          type="button"
          onClick={() => execCommand('bold')}
          className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-100"
          title="粗体"
        >
          <i className="fa-solid fa-bold"></i>
        </button>
        <button
          type="button"
          onClick={() => execCommand('italic')}
          className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-100"
          title="斜体"
        >
          <i className="fa-solid fa-italic"></i>
        </button>
        <button
          type="button"
          onClick={() => execCommand('underline')}
          className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-100"
          title="下划线"
        >
          <i className="fa-solid fa-underline"></i>
        </button>
        
        <div className="w-px bg-gray-300 mx-1"></div>
        
        <button
          type="button"
          onClick={() => execCommand('justifyLeft')}
          className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-100"
          title="左对齐"
        >
          <i className="fa-solid fa-align-left"></i>
        </button>
        <button
          type="button"
          onClick={() => execCommand('justifyCenter')}
          className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-100"
          title="居中对齐"
        >
          <i className="fa-solid fa-align-center"></i>
        </button>
        <button
          type="button"
          onClick={() => execCommand('justifyRight')}
          className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-100"
          title="右对齐"
        >
          <i className="fa-solid fa-align-right"></i>
        </button>
        
        <div className="w-px bg-gray-300 mx-1"></div>
        
        <button
          type="button"
          onClick={() => execCommand('insertUnorderedList')}
          className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-100"
          title="无序列表"
        >
          <i className="fa-solid fa-list-ul"></i>
        </button>
        <button
          type="button"
          onClick={() => execCommand('insertOrderedList')}
          className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-100"
          title="有序列表"
        >
          <i className="fa-solid fa-list-ol"></i>
        </button>
        
        <div className="w-px bg-gray-300 mx-1"></div>
        
        <button
          type="button"
          onClick={insertLink}
          className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-100"
          title="插入链接"
        >
          <i className="fa-solid fa-link"></i>
        </button>
        <button
          type="button"
          onClick={insertImage}
          className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-100"
          title="插入图片"
        >
          <i className="fa-solid fa-image"></i>
        </button>
        <button
          type="button"
          onClick={insertTable}
          className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-100"
          title="插入表格"
        >
          <i className="fa-solid fa-table"></i>
        </button>
        <button
          type="button"
          onClick={insertDocument}
          className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-100"
          title="插入文档"
        >
          <i className="fa-solid fa-file-arrow-up"></i>
        </button>
        
        <div className="w-px bg-gray-300 mx-1"></div>
        
        <button
          type="button"
          onClick={() => execCommand('removeFormat')}
          className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-100"
          title="清除格式"
        >
          <i className="fa-solid fa-eraser"></i>
        </button>
      </div>
      
      {/* 编辑区域 */}
      <div
        ref={editorRef}
        contentEditable={!disabled}
        onInput={handleInput}
        className="p-4 focus:outline-none"
        style={{
          minHeight: height,
          maxHeight: height * 2,
          overflowY: 'auto'
        }}
        suppressContentEditableWarning={true}
      />
      
      {/* 隐藏的文件输入 */}
      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        onChange={handleFileSelect}
        className="hidden"
      />
      <input
        ref={documentInputRef}
        type="file"
        accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx"
        onChange={handleDocumentSelect}
        className="hidden"
      />
    </div>
  );
}
